package com.dmatek.uwb.packet.ianalysis.handler;
import com.dmatek.uwb.packet.ianalysis.IAnalysisLocatorPack;
import com.dmatek.uwb.packet.ianalysis.callback.IReportCallBack;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.socket.DatagramPacket;
/**   
 * @Title: AnalysisPackHandler.java 
 * @Description: TODO
 * @author zhangfu  
 * @date 2019年12月3日 上午11:54:41 
 * @version V1.0   
 */
public class AnalysisPackHandlers extends SimpleChannelInboundHandler<DatagramPacket> {
	private IAnalysisLocatorPack[] iAnalysisLocatorPacks;
	private IReportCallBack<ChannelHandlerContext> iChannelActiveCallBack;
	@SafeVarargs
	public AnalysisPackHandlers(
			IReportCallBack<ChannelHandlerContext> iChannelActiveCallBack,
			IAnalysisLocatorPack... iAnalysisLocatorPacks) {
		super();
		this.iChannelActiveCallBack = iChannelActiveCallBack;
		this.iAnalysisLocatorPacks = iAnalysisLocatorPacks;
	}
	@Override
	protected void channelRead0(ChannelHandlerContext ctx, DatagramPacket datagramPacket)
			throws Exception {
		// 从DatagramPacket对象中获取字节缓存
		ByteBuf byteBuf = datagramPacket.content();
		// 创建一个字节数组
		byte[] bytes = new byte[byteBuf.readableBytes()];
		// 将缓存中的内容读取到字节数组中
		byteBuf.readBytes(bytes);
		try {
			// 通过不同的解析器解析自己的数据包
			for (IAnalysisLocatorPack iAnalysisLocatorPack : iAnalysisLocatorPacks) {
				iAnalysisLocatorPack.analysisPack(bytes, datagramPacket.sender());
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	@Override
	public void channelActive(ChannelHandlerContext ctx) throws Exception {
		// 信道被激活
		if(null != iChannelActiveCallBack) {
			iChannelActiveCallBack.callBack(ctx);
		}
		super.channelActive(ctx);
	}
}
